package com.wfh.rpc.protocal;

import com.wfh.rpc.serializer.Serializer;
import com.wfh.rpc.serializer.SerializerFactory;
import io.vertx.core.buffer.Buffer;

import java.io.IOException;

/**
 * @Title: ProtocolMessageEncoder
 * @Author wangfenghuan
 * @Package com.wfh.rpc.protocal
 * @Date 2025/10/15 08:42
 * @description: 协议消息编码器
 */
public class ProtocolMessageEncoder {

    /**
     * 消息编码
     * @param protocalMessage
     * @return
     * @throws IOException
     */
    public static Buffer encode(ProtocolMessage<?> protocalMessage) throws IOException{
        if (protocalMessage == null || protocalMessage.getHeader() == null){
            return Buffer.buffer();
        }
        ProtocolMessage.Header header = protocalMessage.getHeader();
        // 依次向缓冲区写入字节
        Buffer buffer = Buffer.buffer();
        buffer.appendByte(header.getMagic());
        buffer.appendByte(header.getVersion());
        buffer.appendByte(header.getSerializer());
        buffer.appendByte(header.getType());
        buffer.appendByte(header.getStatus());
        buffer.appendLong(header.getRequestId());

        // 获取序列化器
        ProtocolMessageSerializerEnum serializerEnum = ProtocolMessageSerializerEnum.getEnumByKey(header.getSerializer());
        if (serializerEnum == null){
            throw new RuntimeException("序列化协议不存在");
        }
        Serializer instance = SerializerFactory.getInstance(serializerEnum.getValue());
        byte[] bytes = instance.serialize(protocalMessage.getBody());
        // 写入body长度和数据
        buffer.appendInt(bytes.length);
        buffer.appendBytes(bytes);
        return buffer;
    }

}
